<template>
  <div class="monitoring-container">
    <el-card class="filter-card">
      <template #header>
        <div class="card-header">
          <h3>异常采购监控管理</h3>
          <div class="operation-buttons">
            <el-button type="primary" @click="exportData">导出数据</el-button>
            <el-button type="success" @click="refreshData">刷新数据</el-button>
          </div>
        </div>
      </template>
      
      <el-form :model="filterForm" label-width="100px" :inline="true">
        <el-form-item label="异常类型">
          <el-select v-model="filterForm.exceptionType" placeholder="请选择异常类型" clearable multiple collapse-tags>
            <el-option v-for="item in exceptionTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="订单编号">
          <el-input v-model="filterForm.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        
        <el-form-item label="供应商">
          <el-select v-model="filterForm.supplierId" placeholder="请选择供应商" clearable filterable>
            <el-option v-for="item in supplierOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="处理状态">
          <el-select v-model="filterForm.status" placeholder="请选择处理状态" clearable>
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="发生时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 异常监控列表 -->
    <el-card class="monitoring-list-card">
      <div class="monitoring-statistics">
        <div class="stat-item">
          <div class="stat-title">待处理异常</div>
          <div class="stat-value warning">{{ statistics.pending }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-title">处理中异常</div>
          <div class="stat-value processing">{{ statistics.processing }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-title">已解决异常</div>
          <div class="stat-value success">{{ statistics.resolved }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-title">已关闭异常</div>
          <div class="stat-value info">{{ statistics.closed }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-title">异常总数</div>
          <div class="stat-value">{{ statistics.total }}</div>
        </div>
      </div>
      
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="{background:'#f5f7fa'}"
      >
        <el-table-column type="expand">
          <template #default="props">
            <div class="exception-detail">
              <p><strong>异常描述：</strong>{{ props.row.description }}</p>
              <p><strong>影响分析：</strong>{{ props.row.impact }}</p>
              <p v-if="props.row.solution"><strong>解决方案：</strong>{{ props.row.solution }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="exceptionId" label="异常编号" />
        <el-table-column prop="orderNo" label="关联订单"  />
        <el-table-column prop="exceptionType" label="异常类型" >
          <template #default="scope">
            {{ getExceptionTypeText(scope.row.exceptionType) }}
          </template>
        </el-table-column>
        <el-table-column prop="severity" label="严重程度" width="120">
          <template #default="scope">
            <el-tag :type="getSeverityTagType(scope.row.severity)" effect="dark">
              {{ getSeverityText(scope.row.severity) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="occurTime" label="发生时间" width="180" />
        <el-table-column prop="supplierName" label="供应商" width="180" />
        <el-table-column prop="status" label="处理状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="viewDetail(scope.row)">详情</el-button>
            <el-button type="primary" link @click="handleException(scope.row)" v-if="scope.row.status !== 'closed'">处理</el-button>
            <el-button type="danger" link @click="closeException(scope.row)" v-if="scope.row.status === 'resolved'">关闭</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 异常详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="异常详情"
      width="70%"
      destroy-on-close
    >
      <div v-if="currentException" class="exception-detail-dialog">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="异常编号">{{ currentException.exceptionId }}</el-descriptions-item>
          <el-descriptions-item label="关联订单">{{ currentException.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="异常类型">{{ getExceptionTypeText(currentException.exceptionType) }}</el-descriptions-item>
          <el-descriptions-item label="严重程度">
            <el-tag :type="getSeverityTagType(currentException.severity)" effect="dark">
              {{ getSeverityText(currentException.severity) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="发生时间">{{ currentException.occurTime }}</el-descriptions-item>
          <el-descriptions-item label="处理状态">
            <el-tag :type="getStatusTagType(currentException.status)">
              {{ getStatusText(currentException.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="供应商名称">{{ currentException.supplierName }}</el-descriptions-item>
          <el-descriptions-item label="供应商联系人">{{ currentException.supplierContact }}</el-descriptions-item>
          <el-descriptions-item label="异常描述" :span="2">{{ currentException.description }}</el-descriptions-item>
          <el-descriptions-item label="影响分析" :span="2">{{ currentException.impact }}</el-descriptions-item>
          <el-descriptions-item label="解决方案" :span="2" v-if="currentException.solution">{{ currentException.solution }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider content-position="left">处理记录</el-divider>
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in currentException.activities"
            :key="index"
            :type="activity.type"
            :color="activity.color"
            :timestamp="activity.timestamp"
          >
            {{ activity.content }}
            <p v-if="activity.comment" class="activity-comment">{{ activity.comment }}</p>
          </el-timeline-item>
        </el-timeline>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleException(currentException)" v-if="currentException && currentException.status !== 'closed'">处理异常</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 异常处理弹窗 -->
    <el-dialog
      v-model="handleDialogVisible"
      title="处理异常"
      width="60%"
      destroy-on-close
    >
      <div v-if="currentException" class="handle-exception-form">
        <el-form :model="handleForm" label-width="120px" ref="handleFormRef">
          <el-form-item label="异常编号">
            <el-input v-model="currentException.exceptionId" disabled />
          </el-form-item>
          
          <el-form-item label="异常类型">
            <el-input :value="getExceptionTypeText(currentException.exceptionType)" disabled />
          </el-form-item>
          
          <el-form-item label="处理状态" prop="status">
            <el-select v-model="handleForm.status" placeholder="请选择处理状态">
              <el-option label="处理中" value="processing" />
              <el-option label="已解决" value="resolved" />
              <el-option label="已关闭" value="closed" v-if="currentException.status === 'resolved'" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="处理方案" prop="solution" v-if="handleForm.status === 'resolved'">
            <el-input
              v-model="handleForm.solution"
              type="textarea"
              rows="4"
              placeholder="请输入解决方案"
            />
          </el-form-item>
          
          <el-form-item label="处理备注" prop="comment">
            <el-input
              v-model="handleForm.comment"
              type="textarea"
              rows="3"
              placeholder="请输入处理备注"
            />
          </el-form-item>
          
          <el-form-item label="上传附件">
            <el-upload
              action="#"
              :auto-upload="false"
              :file-list="handleForm.fileList"
              multiple
            >
              <el-button type="primary">选择文件</el-button>
              <template #tip>
                <div class="el-upload__tip">请上传相关支持文件，支持PDF、Word、Excel等格式</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHandleForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'ExceptionMonitoring',
  setup() {
    // 状态和数据
    const loading = ref(false)
    const tableData = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const detailVisible = ref(false)
    const handleDialogVisible = ref(false)
    const currentException = ref(null)
    
    // 处理表单
    const handleForm = reactive({
      status: '',
      solution: '',
      comment: '',
      fileList: []
    })
    const handleFormRef = ref(null)
    
    // 筛选表单
    const filterForm = reactive({
      exceptionType: [],
      orderNo: '',
      supplierId: '',
      status: '',
      dateRange: []
    })
    
    // 异常类型选项
    const exceptionTypeOptions = [
      { value: 'delivery_delay', label: '交付延迟' },
      { value: 'quality_issue', label: '质量问题' },
      { value: 'price_change', label: '价格变动' },
      { value: 'quantity_mismatch', label: '数量不符' },
      { value: 'specification_mismatch', label: '规格不符' },
      { value: 'payment_issue', label: '付款问题' },
      { value: 'contract_breach', label: '合同违约' },
      { value: 'communication_issue', label: '沟通问题' }
    ]
    
    // 供应商选项
    const supplierOptions = [
      { value: 'S001', label: '上海钢铁有限公司' },
      { value: 'S002', label: '江苏精密机械制造有限公司' },
      { value: 'S003', label: '广东电子科技有限公司' }
    ]
    
    // 处理状态选项
    const statusOptions = [
      { value: 'pending', label: '待处理' },
      { value: 'processing', label: '处理中' },
      { value: 'resolved', label: '已解决' },
      { value: 'closed', label: '已关闭' }
    ]
    
    // 统计数据
    const statistics = reactive({
      pending: 0,
      processing: 0,
      resolved: 0,
      closed: 0,
      total: 0
    })
    
    // 获取异常类型文本
    const getExceptionTypeText = (type) => {
      const found = exceptionTypeOptions.find(item => item.value === type)
      return found ? found.label : '未知类型'
    }
    
    // 获取严重程度标签类型
    const getSeverityTagType = (severity) => {
      const typeMap = {
        'high': 'danger',
        'medium': 'warning',
        'low': 'info'
      }
      return typeMap[severity] || 'info'
    }
    
    // 获取严重程度文本
    const getSeverityText = (severity) => {
      const textMap = {
        'high': '高',
        'medium': '中',
        'low': '低'
      }
      return textMap[severity] || '未知'
    }
    
    // 获取状态标签类型
    const getStatusTagType = (status) => {
      const typeMap = {
        'pending': 'warning',
        'processing': 'primary',
        'resolved': 'success',
        'closed': 'info'
      }
      return typeMap[status] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const textMap = {
        'pending': '待处理',
        'processing': '处理中',
        'resolved': '已解决',
        'closed': '已关闭'
      }
      return textMap[status] || '未知状态'
    }
    
    // 查看异常详情
    const viewDetail = (exception) => {
      currentException.value = exception
      detailVisible.value = true
    }
    
    // 处理异常
    const handleException = (exception) => {
      currentException.value = exception
      handleForm.status = exception.status === 'pending' ? 'processing' : exception.status
      handleForm.solution = exception.solution || ''
      handleForm.comment = ''
      handleForm.fileList = []
      handleDialogVisible.value = true
    }
    
    // 提交处理表单
    const submitHandleForm = () => {
      if (!handleForm.comment) {
        ElMessage.warning('请输入处理备注')
        return
      }
      
      if (handleForm.status === 'resolved' && !handleForm.solution) {
        ElMessage.warning('请输入解决方案')
        return
      }
      
      // 实际项目中这里应该调用API处理异常
      // 模拟API调用
      setTimeout(() => {
        ElMessage.success('异常处理成功')
        handleDialogVisible.value = false
        loadData() // 重新加载数据
      }, 800)
    }
    
    // 关闭异常
    const closeException = (exception) => {
      ElMessageBox.confirm('确定要关闭此异常吗？关闭后将不能再进行处理。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 实际项目中这里应该调用API关闭异常
        // 模拟API调用
        setTimeout(() => {
          ElMessage.success('异常已关闭')
          loadData() // 重新加载数据
        }, 800)
      }).catch(() => {})
    }
    
    // 导出数据
    const exportData = () => {
      ElMessage.success('数据导出成功')
    }
    
    // 刷新数据
    const refreshData = () => {
      loadData()
    }
    
    // 加载数据
    const loadData = () => {
      loading.value = true
      // 实际项目中这里应该调用API获取异常数据
      // 模拟API调用
      setTimeout(() => {
        // 模拟数据
        tableData.value = [
          {
            exceptionId: 'EX-20230601-001',
            orderNo: 'PO-20230501-001',
            exceptionType: 'delivery_delay',
            severity: 'high',
            occurTime: '2023-06-01 09:15:30',
            supplierName: '上海钢铁有限公司',
            supplierContact: '张经理 (13800138001)',
            status: 'resolved',
            description: '供应商未能按照合同约定的时间交付物料，导致生产计划延迟。原定交付日期为2023-05-15，截至目前仍未收到全部物料。',
            impact: '影响生产线A的正常运行，可能导致产品交付延期，预计影响3天生产计划。',
            solution: '与供应商协商加急发货，并调整生产计划，优先使用现有库存完成部分生产任务。',
            activities: [
              { content: '发现异常', comment: '系统自动检测到交付延迟', timestamp: '2023-06-01 09:15:30', type: 'warning', color: '#E6A23C' },
              { content: '开始处理', comment: '已联系供应商了解情况', timestamp: '2023-06-01 10:30:45', type: 'primary', color: '#409EFF' },
              { content: '解决方案', comment: '供应商承诺加急发货，预计6月3日可以全部到货', timestamp: '2023-06-02 14:20:15', type: 'success', color: '#67C23A' }
            ]
          },
          {
            exceptionId: 'EX-20230605-002',
            orderNo: 'PO-20230510-002',
            exceptionType: 'quality_issue',
            severity: 'medium',
            occurTime: '2023-06-05 14:30:22',
            supplierName: '江苏精密机械制造有限公司',
            supplierContact: '李工 (13900139002)',
            status: 'processing',
            description: '收到的轴承样品不符合质量标准，经检测发现有5%的产品存在尺寸偏差问题。',
            impact: '可能影响最终产品的质量和稳定性，需要进行全检并退回不合格产品。',
            solution: '',
            activities: [
              { content: '发现异常', comment: '质检部门报告发现质量问题', timestamp: '2023-06-05 14:30:22', type: 'warning', color: '#E6A23C' },
              { content: '开始处理', comment: '已通知供应商并要求提供解释和解决方案', timestamp: '2023-06-05 16:45:10', type: 'primary', color: '#409EFF' }
            ]
          },
          {
            exceptionId: 'EX-20230610-003',
            orderNo: 'PO-20230520-003',
            exceptionType: 'price_change',
            severity: 'low',
            occurTime: '2023-06-10 11:20:15',
            supplierName: '广东电子科技有限公司',
            supplierContact: '王总 (13700137003)',
            status: 'pending',
            description: '供应商通知原材料价格上涨15%，要求调整合同价格，否则无法按原价供货。',
            impact: '如接受涨价，将增加采购成本约2万元；如不接受，可能需要重新寻找供应商，导致交付延期。',
            solution: '',
            activities: [
              { content: '发现异常', comment: '供应商发来价格调整通知', timestamp: '2023-06-10 11:20:15', type: 'warning', color: '#E6A23C' }
            ]
          }
        ]
        
        // 更新统计数据
        statistics.pending = tableData.value.filter(item => item.status === 'pending').length
        statistics.processing = tableData.value.filter(item => item.status === 'processing').length
        statistics.resolved = tableData.value.filter(item => item.status === 'resolved').length
        statistics.closed = tableData.value.filter(item => item.status === 'closed').length
        statistics.total = tableData.value.length
        
        total.value = tableData.value.length
        loading.value = false
      }, 800)
    }
    
    // 处理页面大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size
      loadData()
    }
    
    // 处理页码变化
    const handleCurrentChange = (page) => {
      currentPage.value = page
      loadData()
    }
    
    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
      loadData()
    }
    
    // 重置表单
    const resetForm = () => {
      filterForm.exceptionType = []
      filterForm.orderNo = ''
      filterForm.supplierId = ''
      filterForm.status = ''
      filterForm.dateRange = []
      handleSearch()
    }
    
    // 初始化
    onMounted(() => {
      loadData()
    })
    
    return {
      // 状态
      loading,
      tableData,
      currentPage,
      pageSize,
      total,
      detailVisible,
      handleDialogVisible,
      currentException,
      handleForm,
      handleFormRef,
      filterForm,
      exceptionTypeOptions,
      supplierOptions,
      statusOptions,
      statistics,
      
      // 方法
      getExceptionTypeText,
      getSeverityTagType,
      getSeverityText,
      getStatusTagType,
      getStatusText,
      viewDetail,
      handleException,
      submitHandleForm,
      closeException,
      exportData,
      refreshData,
      loadData,
      handleSizeChange,
      handleCurrentChange,
      handleSearch,
      resetForm
    }
  }
}
</script>

<style>
.monitoring-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

.monitoring-list-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.monitoring-statistics {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.stat-item {
  background-color: #f5f7fa;
  padding: 15px 20px;
  border-radius: 4px;
  text-align: center;
  min-width: 150px;
  flex: 1;
  margin: 0 5px 10px;
}

.stat-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-value.warning {
  color: #E6A23C;
}

.stat-value.processing {
  color: #409EFF;
}

.stat-value.success {
  color: #67C23A;
}

.stat-value.info {
  color: #909399;
}

.exception-detail {
  padding: 10px 20px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.exception-detail p {
  margin: 8px 0;
}

.exception-detail-dialog .el-descriptions {
  margin-bottom: 20px;
}

.activity-comment {
  color: #606266;
  font-size: 13px;
  margin-top: 5px;
  margin-bottom: 0;
}

/* 设置所有下拉框宽度为180px */
.el-select {
  width: 180px !important;
}

/* 特殊情况下需要100%宽度的select */
.full-width-select .el-select {
  width: 100% !important;
}
</style>